import { request, uploadRequest } from '@/service/request/request';
import userStore from '@/store/user';

/**
 * 用户登陆服务
 * @param {account: string, password: string} data
 */
export const login = async (data) => {
    try {
        const token = await request('/user/login', data);
        if (!token) {
            throw new Error('请求数据失败');
        }
        // 通过登陆接口获取用户token
        wx.setStorageSync('token', token);
        await autoLogin(token);
    } catch (err) {
        throw err;
    }
};

/**
 * 根据token自动登陆并获取用户信息接口
 * @param {*} token
 */
export const autoLogin = async (token) => {
    try {
        const userInfo = await request('/user/profile', null);
        if (!userInfo) {
            throw new Error('获取用户数据失败');
        }
        userStore.setUserInfo(userInfo);
    } catch (err) {
        throw err;
    }
};

/**
 * 用户注册服务
 */
export const register = async (data) => {
    try {
        await request('/user/register', data);
    } catch (err) {
        throw err;
    }
};

/**
 * 获取邮箱验证码
 * @param {string} email
 */
export const getValidateCode = async (email) => {
    try {
        await request('/user/senMailCode', { mail: email });
    } catch (err) {
        throw err;
    }
};

/**
 * 验证邮箱验证码是否正确
 * @param {string} email
 * @param {string} code
 */
export const checkValidateCode = async (email, code) => {
    try {
        await request('/user/verifyCode', { email: email, code: code });
    } catch (err) {
        throw err;
    }
};

/**
 * 修改用户信息
 * @param {*} data
 */
export const updateUser = async (data) => {
    try {
        const token = wx.getStorageSync('token');
        await request('/user/edit', data);
    } catch (err) {
        throw err;
    }
};

/**
 * 重置用户密码接口
 * @param {*} account
 * @param {*} password
 * @param {*} code
 */
export const resetUserPassword = async (data) => {
    try {
        await request('/user/change-password', data);
    } catch (err) {
        throw err;
    }
};

/**
 * 更新用户头像
 * @param {*} data
 */
export const updateUseravatar = async (data, filePath) => {
    try {
        return await uploadRequest('/user/file/avatar', 'image', data, filePath);
    } catch (err) {
        throw err;
    }
};
